import React, { Component } from "react";
import { Spin, Row, Checkbox, Form, Input } from 'antd';
import NoticeUserAddTable from "components/NoticeUserAddTable";
import { openNotificationWithIcon, updateNoticeUser } from "utils/comm"
import styles from "./TransferForm.less";

class FlowHandleBaseForm extends Component {
  constructor(props) {
    super(props)
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
  }

  getTreeRef = (treeThis) => {
    this.treeRef = treeThis;
  };

  getTaskId = () => {
    const { taskId } = this.props;
    return taskId;
  }

  getApplyUserId = () => {
    const { applyUserId } = this.props;
    return applyUserId;
  }

  clearCheckNodes = () => {
    this.checkedKeys = [];
    const { checkedNodes, noticeUsers } = this.state;
    this.setState({ checkedNodes: [], noticeUsers: updateNoticeUser(checkedNodes, noticeUsers, false) });
  };

  tagClose = (removedTag) => {
    const { checkedNodes } = this.state;
    const aftercheckedNodes = checkedNodes.filter((tag) => tag !== removedTag);
    this.checkedKeys = aftercheckedNodes.map((item) => item.key);
    const { noticeUsers, addCheckNodeToNoticeUser } = this.state;
    let newNoticeUsers;
    if (addCheckNodeToNoticeUser) {
      newNoticeUsers = noticeUsers.filter(({ userCode }) => userCode !== removedTag.key);
    } else {
      newNoticeUsers = noticeUsers;
    }
    this.setState({ checkedNodes: aftercheckedNodes, noticeUsers: newNoticeUsers });
  };

  noticeTagClose = (removedTag) => {
    const { noticeUsers } = this.state;
    const newNoticeUsers = noticeUsers.filter((tag) => tag.userCode !== removedTag.userCode);
    this.setState({ noticeUsers: newNoticeUsers });
  };

  doCheckTree = (checkedKeys, checkedNodes) => {
   
    this.checkedKeys = checkedKeys;
    const { checkedNodes: prevCheckNodes, noticeUsers, addCheckNodeToNoticeUser } = this.state;
    
    const prevCheckNodeMap = prevCheckNodes.reduce((map, { key }) => {
      map[key] = true;
      return map;
    }, {});
    const customNoticeUsers = noticeUsers.filter(({ userCode }) => !prevCheckNodeMap[userCode]);
    
    this.setState({ checkedNodes, noticeUsers: addCheckNodeToNoticeUser ? updateNoticeUser(checkedNodes, customNoticeUsers, true) : noticeUsers });
  };

  handleNoticeUserOk = (users) => {
    const { checkedNodes } = this.state;
    const noticeUserKeyMap = users.reduce((map, { userCode }) => {
      map[userCode] = true;
      return map;
    }, {}); 
    const addCheckNodeToNoticeUser = (checkedNodes || []).every(({ key }) => noticeUserKeyMap[key]);
    this.setState({ noticeUsers: users, addCheckNodeToNoticeUser })
  }

  // 用于展示消息接收人tags
  getCustomNoticeUsers = () => {
    const { checkedNodes,  noticeUsers } = this.state;
    return (noticeUsers || []).filter(({ userCode }) => !(checkedNodes || []).some(({ key }) => key === userCode))
  }

  loadMessageTheme = () => {
    const { form, loadMessageTheme, noticeThemeTypeList } = this.props;
    const noticeThemeTypes = (noticeThemeTypeList || []).filter(({ value }) => (value || '').indexOf(this.noticeKey) > -1);
    if (noticeThemeTypes.length > 0) {
      loadMessageTheme(
        'NODE',
        noticeThemeTypes[0].key,
      ).then(({ datas }) => {
        if (datas && datas.length > 0) {
          form.setFieldsValue({ messageThemName: datas[0].messageThemName });
        }
        form.validateFields();
      });
    } else {
      form.validateFields();
    }
  }

  renderNoticeTheme = () => {
    const { form, loadingMessageTheme } = this.props;
    const { getFieldDecorator } = form;
    return (
      <Spin spinning={!!loadingMessageTheme}>
        <div>
          <div className={[styles.formLabel, 'dynamic-color'].join(' ')}>通知消息主题：</div>
          <Form.Item label="">
            {getFieldDecorator("messageThemName", {
              rules: [
                { required: true, message: "请联系管理员配置对应的通知消息主题" },
              ],
            })(<Input disabled />)}
          </Form.Item>
        </div>
      </Spin>
    );
  }

  renderAddCheckUsers(title, customUsers,disabled) {
    if (!title) return null;
    const {
      addCheckNodeToNoticeUser,
      noticeUsers,
    } = this.state;
    const indeterminate = !addCheckNodeToNoticeUser && customUsers.length < noticeUsers.length;
    return (
      <Checkbox
        checked={addCheckNodeToNoticeUser}
        onChange={(e) => {
          const { checkedNodes: selectUsers, noticeUsers: _noticeUsers } = this.state;
          this.setState({
            addCheckNodeToNoticeUser: e.target.checked,
            noticeUsers: updateNoticeUser(selectUsers, _noticeUsers, e.target.checked),
          });
        }}
        indeterminate={indeterminate}
        disabled={disabled}
      >
        {title}
      </Checkbox>
    )
  }

  renderNoticeUsers() {
    const { noticeUsers, noticeUserSelectorVisible } = this.state;
   
    return (
      <Row type="flex" align="middle">
        {
          noticeUserSelectorVisible && (
            <NoticeUserAddTable
              handleCancel={() => this.setState({ noticeUserSelectorVisible: false })}
              onOk={this.handleNoticeUserOk}
              visible={noticeUserSelectorVisible}
              onfirmLoading={false}
              users={noticeUsers}
            />
        )}
      </Row>
    );
  }

}

export default FlowHandleBaseForm;